package com.winchain.chainbill.basic.invoice.rx;

import com.shell.bee.invoince.po.InvDfr;
import com.shell.bee.invoince.service.InvDfrService;
import com.shell.constant.rel.AssetCode;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.shell.framework.utils.CommonDataUtil;
import com.shell.framework.utils.MessageSender;
import com.shell.framework.utils.SysDateUtil;
import com.shell.governor.modules.message.keyword.InvoiceOverdueUploadRestoreQuotaKeyWord;
import com.winchain.chainbill.tbill.base.dao.TbDctDao;
import com.winchain.chainbill.tbill.base.po.TbDct;
import com.winchain.chainbill.tbill.base.po.TbRec;
import com.winchain.chainbill.tbill.base.po.TbSnd;
import com.winchain.chainbill.tbill.base.service.TbRecService;
import com.winchain.chainbill.tbill.base.service.TbSndService;
import com.winchain.chainbill.tbill.biz.TBill;
import com.winchain.chainbill.tbill.biz.TBillEvent;
import com.winchain.chainbill.trade.service.BillAcctBlcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TBillInvoiceDfrOverdueUploadSubscriber extends OnErrorNotImplementedSubscriber<TBillEvent<TbDct>> {
	@Autowired
	private InvDfrService invDfrService;
	@Autowired
	private TbRecService tbRecService;
	@Autowired
	private TbSndService tbSndService;
	@Autowired
	private TbDctDao tbDctDao;
	@Autowired
	private BillAcctBlcService billAcctBlcService;

	public void onApplicationEvent(TBillEvent<TbDct> t) {
		TbDct dct = (TbDct) t.getBill().getSource();
		if (dct == null) {
			return;
		}
		InvDfr invDfr = this.invDfrService.selectByBiz(dct.getDctId(), "2");
		boolean overdue = this.invDfrService.isOverdue(invDfr);
		if (overdue) {
			TbRec rec = (TbRec) this.tbRecService.selectByKey(dct.getBillId());
			TbSnd snd = this.tbSndService.selectByBillId(rec.getRootId());
			int count = this.tbDctDao.countOverdueUploadInvoice(snd.getBuyerId(), SysDateUtil.getSystemDate());
			if (count == 0) {
				this.billAcctBlcService.updateAcctBkpState(dct.getFinId(), snd.getBuyerId(), AssetCode.FQT.name(), "42",
						"1");

				String template = "MT05006";
				InvoiceOverdueUploadRestoreQuotaKeyWord keyWord = new InvoiceOverdueUploadRestoreQuotaKeyWord();
				String sendId = CommonDataUtil.getUserId();
				MessageSender.sendMessageByTmpl(sendId, template, keyWord, snd.getBuyerId());
			}
		}
	}
}
